<template>
	<div id="stDetail" class="sceneDetail" style="padding:30px;">
        <div style="margin: 0 0 20px 0" class="sceneStep">
            <template>
                <div style="display: flex;justify-content: space-between;">
                    <Steps :current="currentIndex" style="width: 50%;">
                        <Step title="训练前设置" @click.native="toPreCompeManage" content="提供体验前成员、接入机的管理"  
                            :class="{curStep : sceneStatus === 'initialized'}" :icon="sceneStatus === 'initialized' ? 'ios-refresh-circle':''">
                        </Step>
                        <Step title="训练中管理" @click.native="toCompeingManage" content="提供体验中的成员、接入机的管理"  
                            :class="{curStep : sceneStatus === 'running'}" :icon="sceneStatus === 'running' ? 'ios-refresh-circle':''">
                        </Step>
                        <Step title="训练后归档" @click.native="toCompeedManage" content="提供体验后的归档"  :class="{curStep : sceneStatus === 'stopped'}" 
                            :icon="sceneStatus === 'stopped'? 'ios-refresh-circle':''">
                        </Step>
                    </Steps>
                    <div style="width: 50%;">
                        <div style="display:flex;justify-content: flex-end;">
                            <Poptip
                                confirm placement="top"
                                :title="tipText" word-wrap width="300"
                                transfer @on-ok="startScene('start')">
                                <Button type="primary" :disabled="!startContestStatus">
                                    <img src="../../../assets/scene/start-scene.png" alt="" v-if="startContestStatus" />
                                    <img src="../../../assets/scene/dis-start-scene.png" alt="" v-else />
                                    开始体验</Button>
                            </Poptip>
                            <Poptip
                                confirm
                                title="确定要结束训练吗？"
                                transfer @on-ok="startScene('stop')"
                                word-wrap>
                                <Button type="primary" :disabled="!stopContestStatus" style="margin-left: 10px;">
                                    <img src="../../../assets/scene/stop-scene.png" alt="" v-if="stopContestStatus"/>
                                    <img src="../../../assets/scene/dis-stop-scene.png" alt="" v-else/>
                                    结束体验
                                </Button>
                            </Poptip>
                            <Poptip
                                confirm
                                title="确定要重新开始吗？"
                                transfer @on-ok="startScene('init')"
                                word-wrap>
                                <Button type="primary" :disabled="!stopedStatus" style="margin-left: 10px;">
                                    <img src="../../../assets/scene/reset-compete.png" alt="" v-if="stopedStatus"/>
                                    <img src="../../../assets/scene/dis-switch-network.png" alt="" v-else/>
                                    重新开始
                                </Button>
                            </Poptip>
                            <Poptip
                                confirm
                                title="确定要归档吗？"
                                transfer @on-ok="guidang"
                                word-wrap>
                                <Button type="primary" :disabled="!stopedStatus" style="margin-left: 10px;font-size: 12px;">
                                    <Icon size='22' type="md-copy" />归档
                                </Button>
                            </Poptip>
                            <Button type="primary" :disabled="!stopedStatus" style="margin-left: 10px;font-size: 12px;" @click='lookUpReport'>
                                <img src="../../../assets/scene/btn-report.png">报告
                            </Button>
                        </div>
                    </div>
                </div>
            </template>
        </div>
        <div class="scene-content">
            <!-- 赛前 -->
            <Tabs class="demo-tabs-style2" v-if="preCompeManagePanelShow" @on-click="changePreTab" :value="preDefault">
                <TabPane label="用户接入" name="accessGroup">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <AccessUserToGroup ref="childMethod" ></AccessUserToGroup>  
                    </div>
                </TabPane>
                <TabPane label="用户接入设备" name="guide">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <UserLinkDevice v-if="preDefault == 'guide'"></UserLinkDevice>
                    </div>
                </TabPane>
                <TabPane label="设备管理" name="device">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <DevicesList  v-if="preDefault == 'device'"></DevicesList>
                    </div>
                </TabPane>
                <TabPane label="训练任务" name="task">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <TaskList ref="childMethod2" :hidebtn='hideModifyBtn' :isImport='trainInfo.isImport'></TaskList>
                    </div>
                </TabPane>
                <TabPane label="采集任务" name="collect">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <CollectTask  v-if="preDefault == 'collect'"></CollectTask>
                    </div>
                </TabPane>
                <TabPane label="验证任务" name="check">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <CheckTask  v-if="preDefault == 'check'"></CheckTask>
                    </div>
                </TabPane>
                <TabPane label="任务分配" name="branch">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <BranchTask  v-if="preDefault == 'branch'" :isImport='trainInfo.isImport'></BranchTask>
                    </div>
                </TabPane>
            </Tabs>
            <!-- 赛中 -->
            <Tabs class="demo-tabs-style2" v-if="compeingManagePanelShow" @on-click="changeMidTab" :value="midDefault">
                <TabPane label="用户接入设备" name="guide">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <UserLinkDevice v-if="midDefault == 'guide'"></UserLinkDevice>
                    </div>
                </TabPane>
                <TabPane label="训练任务" name="task">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <TaskList v-if="midDefault == 'task'" :hidebtn='hideModifyBtn' :isImport='trainInfo.isImport'></TaskList>
                    </div>
                </TabPane>
                <TabPane label="学员完成进度" name="progress">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <UserTask v-if="midDefault == 'progress'"></UserTask>
                    </div>
                </TabPane>
                <TabPane label="设备管理" name="device">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <DevicesList v-if="midDefault == 'device'"></DevicesList>
                    </div>
                </TabPane>
                <TabPane label="选手接入机器录屏" name="video">
                    <screenController v-if ="midDefault == 'video'" ></screenController>
                </TabPane>
            </Tabs>
            <!-- 赛后 -->
            <Tabs class="demo-tabs-style2" v-if="compeedManagePanelShow" @on-click="changeEndTab" :value="endDefault">
                <TabPane label="学员完成进度" name="progress">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <UserTask v-if="endDefault == 'progress'"></UserTask>
                    </div>
                </TabPane>
                <TabPane label="训练回放" name="video">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <!-- <DevicesList v-if="endDefault == 'device'"></DevicesList> -->
                    </div>
                </TabPane>
                <TabPane label="分值修改记录" name="midifyScore">
                    <div class="tab-contet" :style='{height:setTabHei}'>
                        <RecordScore v-if="endDefault == 'midifyScore'"></RecordScore>
                    </div>
                </TabPane>
            </Tabs>
        </div>
    </div>
</template>
<script>
    import AccessUserToGroup from '@/view/train/components/accessUserToGroup'
    import UserLinkDevice from '@/view/train/components/userLinkDevice'
    import TaskList from '@/view/train/components/taskList'
    import DevicesList from '@/view/train/components/devices'
    import UserTask from '@/view/train/components/userTaskCompete'
    import CheckTask from '@/view/train/components/checkTask'
    import CollectTask from '@/view/train/components/collectTask'
    import BranchTask from '@/view/train/components/branchTask'
    import screenController from '@/view/train/components/screenController'
    import RecordScore from '@/view/train/components/recordScore'
    import {startSceneBind,sceneInfo,guidang,getTrainById} from '@/api/train.js'
	export default {
	    name: 'sceneDetail',
	    components:{
            AccessUserToGroup,
            UserLinkDevice,
            TaskList,
            DevicesList,
            UserTask,
            CollectTask,
            CheckTask,
            BranchTask,
            screenController,
            RecordScore,
        },
		data(){
            return {
                // 用户id
                USER_ID:'',
                // 接收的id
                scenarioId:this.$route.query.id,
                projectId:this.$route.query.projectId,
                sceneName:this.$route.query.name,
                testId:this.$route.query.testId,
                sceneStatus:'',
                // 内容区高度
                fullHeight:document.documentElement.clientHeight,
                fullWidth:document.documentElement.clientWidth,
                setTabHei:"auto",
                // 训练/场景信息
                sceneInfo:{},
                // 训练信息
                trainInfo:{},
                // 标签显示内容
                preDefault:'',
                midDefault:'',
                endDefault:'',
                currentIndex:0,
                preCompeManagePanelShow:false,
                compeingManagePanelShow:false,
                compeedManagePanelShow:false,
                // 比赛情况
                startContestStatus:true,
                stopContestStatus:false,
                stopedStatus:false,   
                // 课件开始前提示文字
                tipText:'确定要开始训练吗？',
                hideModifyBtn:true,
                // 轮询场景
                querySceneInterval:null,
            }
	    },
	    beforeRouteLeave (to, from, next) {
	        if(to.path === '/trainScene'){
	            //to.query.page = this.$route.query.page
	            next()
	        }else {
	        	//跳转至非训练场景页面，清空存储的查询条件
				sessionStorage.removeItem("queryObj");
	            next()
	        }
	    },
        created(){
            // 获取用户id
            // this.USER_ID = this.$store.state.user.userId
        },
        mounted(){
            this.setStyle()
            window.onresize = () => {
                this.setStyle()
            }
            clearInterval(this.querySceneInterval)
            // 训练信息
            this.getTrainById()
            // 查询场景的信息
            this.getSceneInfo()
            // 轮询场景状态
            this.getSceneStatus()
        },
        beforeDestroy() {
            clearInterval(this.querySceneInterval)
        },
        methods:{
            // 设置高度
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.setTabHei = this.fullHeight - 278 + 'px'
            },
            // 查询训练数据
            getTrainById(){
                getTrainById(this.scenarioId)
                .then(res=>{
                    if(res.data.code === 1){
                        this.trainInfo = res.data.data
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            }, 
            // 查询场景信息
            getSceneInfo(){
                sceneInfo(this.testId)
                .then(res=>{
                    if(res.data.code === 1){
                        this.sceneStatus = res.data.data.status
                        this.setStatus(res.data.data.status)
                    }else{
                        this.$Message.error({
                            content:'场景信息获取失败',
                            duration:5,
                        })
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 设置场景状态
            setStatus(status){
                switch (status){
                    case 'stopped':  // 已停止
                        this.stopedStatus = true
                        this.startContestStatus = false;
                        this.stopContestStatus = false;
                        this.hideModifyBtn = false
                        this.toCompeedManage()
                        clearInterval(this.querySceneInterval)
                        break;
                    case 'running':  // running
                        this.stopedStatus = false
                        this.startContestStatus = false;
                        this.stopContestStatus = true;
                        this.hideModifyBtn = false
                        this.toCompeingManage()
                        break;
                    case 'initialized':  // 初始化
                        this.stopedStatus = false
                        this.startContestStatus = true;
                        this.stopContestStatus = false;
                        this.hideModifyBtn = true
                        this.toPreCompeManage()
                        clearInterval(this.querySceneInterval)
                        break;
                }
            },
            toPreCompeManage(){ // 训练前
                this.preDefault = 'accessGroup';
                this.midDefault = '';
                this.endDefault = '';
                this.currentIndex = 0;
                setTimeout(() => {
                    this.preCompeManagePanelShow = true;
                    this.compeingManagePanelShow = false;
                    this.compeedManagePanelShow = false;
                })
            },
            toCompeingManage(){ // 训练中
                if(this.sceneStatus === 'initialized'){
                    return false
                }
                this.preDefault = '';
                this.midDefault = 'guide';
                this.endDefault = '';
                this.currentIndex = 1;
                setTimeout(() => {
                    this.preCompeManagePanelShow = false;
                    this.compeingManagePanelShow = true;
                    this.compeedManagePanelShow = false;
                })
            },
            toCompeedManage() { // 训练后
                if(this.sceneStatus === 'initialized' || this.sceneStatus === 'running'){
                    return false
                }
                this.preDefault = '';
                this.midDefault = '';
                this.endDefault = 'progress';
                this.currentIndex = 2;
                setTimeout(() => {
                    this.preCompeManagePanelShow = false;
                    this.compeingManagePanelShow = false;
                    this.compeedManagePanelShow = true;
                })
            },
            // 轮询场景状态
            getSceneStatus(){
                this.querySceneInterval = setInterval(() => {
                    sceneInfo(this.testId)
                    .then(res=>{
                        if(res.data.code === 1){
                            let status = res.data.data.status
                            this.sceneStatus = status
                            if(status == 'stopped'){
                                this.setStatus(status)  
                            }
                        }else{
                            this.$Message.error({
                                content:'场景信息获取失败',
                                duration:5,
                            })
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
                }, 5000);
            },
            // 试验场景操作
            startScene(operation){
                let params = {
                    id:this.testId,
                    operation:operation,
                }
                startSceneBind(params)
                .then(res=>{
                    if(res.data.code === 1){
                        if(operation === 'start'){
                            this.sceneStatus = 'running'
                            clearInterval(this.querySceneInterval)
                            this.getSceneStatus()
                            this.setStatus('running')
                        }else if(operation === 'stop'){
                            this.sceneStatus = 'stopped'
                            this.setStatus('stopped')
                        }else if(operation === 'init'){
                            this.sceneStatus = 'initialized'
                            this.setStatus('initialized')
                        }
                    }else{
                        this.$Message.error({content:res.data.message,duration:5})
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 点击标签页
            changePreTab(name){
                this.hideModifyBtn = true
                this.preDefault = name;
            },
            changeMidTab(name){
                this.hideModifyBtn = false
                this.midDefault = name;
            },
            changeEndTab(name){
                this.hideModifyBtn = false
                this.endDefault = name;
            },
            // 归档
            guidang(){
                guidang(this.scenarioId)
                .then(res=>{
                    console.log(res)
                    if(res.data.code === 1){
                        this.$Message.success({
                            content:'归档成功！',
                            duration:3,
                        })
                    }else{
                        this.$Message.error({
                            content:res.data.message,
                            duration:5,
                        })
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 报告
            lookUpReport(){
                const { href } = this.$router.resolve({
                    name:'trainReport',
                    query:{
                        id:this.$route.query.id
                    }
                });
                window.openTrain(href, '_blank')
            },
        }
    }
</script>
<style scoped>
.tab-contet{
    overflow-x: auto;
    padding: 0 2px;
}
    .sceneDetail .demo-table-info-row>td{
		background:lightblue
	}
	
	.sceneDetail .ivu-table-overflowX{
		overflow-x: hidden;
	}
	.sceneDetail .curStep .ivu-steps-icon.ivu-icon.ivu-icon-ios-refresh-circle{
		font-size:30px;
		width:30px;
		height:30px;
		color:#19be6b!important;
		background: url('../../../assets/scene/scene-process.gif') no-repeat;
    }
    .sceneDetail .curStep .ivu-steps-icon.ivu-icon.ivu-icon-ios-refresh-circle:before{
    	content:''
    }
    .sceneDetail .ivu-steps-horizontal .ivu-steps-title:after{
    	height:0;
    	border-top:2px dashed #ccc;
    	background: #fff;
    }
    .sceneDetail .ivu-steps-horizontal .ivu-steps-status-finish .ivu-steps-title:after{
    	background:#fff;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .sceneDetail .sceneStep{
    	position: relative;
    	background:#fff;
    	padding:20px;
    	box-shadow: 0 1px 5px #ccc;
    	border-radius: 5px;
    }
    .sceneDetail .ivu-steps-item.ivu-steps-status-process .ivu-steps-title{
        color: #2b61db;
    }
    .sceneDetail .ivu-steps-item.ivu-steps-status-process .ivu-steps-content{
        color: #9eb0e9;
    }
    .scene-content{
        position: relative;
    	background:#fff;
    	box-shadow: 0 1px 5px #ccc;
    	border-radius: 5px;
        padding: 20px;
    }
    .sceneDetail .btn-group{
    	/* margin-top:20px; */
    }
    .sceneDetail .ivu-btn:not(.ivu-btn-small){
    	padding:5px 10px 6px;
    }
    .sceneDetail .ivu-btn img{
    	position: relative;
    	top:-1px;
    	vertical-align: middle;
    	padding-right: 5px;
    }
    .sceneDetail .addressIcon{
        display: inline-block;
        height: 14px;
        width: 12px;
        background: url("../../../assets/globalIcon/addressIcon.png") no-repeat center;
        background-size: 100% 100%;
        margin-bottom: -1px;
    }
    .sceneDetail .countdown{
    	position: absolute;
	    top: -4px;
	    right: 0px;
    	width: 227px;
	    height: 46px;
	    line-height: 46px;
	    text-align: center;
	    background: url('../../../assets/scene/countdown-bg.png') no-repeat center;
	    color: #fff;
    }
    .sceneDetail .countdown b{
    	font-size:16px;
    }
</style>